import { AesEncode } from './aes'
// import { reportParams, basicConfig } from './config'

import Utils from './Util'

declare var wx;

const { ccclass, property } = cc._decorator;

// 存储版本信息
// const osVersion = wx.getAppBaseInfo().SDKVersion
// const DeviceInfo = wx.getDeviceInfo()
// 设备详情 如宽高
let systemInfo = {}
// 全局参数
let globalQuery = {}
/**
 * 静态上报所需全局参数 
 */
const reportParams = {
  encryption: 0,
  appName: '花田小农场',
  screenWidth: '',
  screenHeight: '',
  appVersion: '3.0.1',
  sdkVersion: '2.0.0',
  vvid: Utils._newVvid(),
  uuid: Utils._newUuid(),
  // osVersion: osVersion,
  // osType: DeviceInfo.system.indexOf('iOS') !== -1 ? "ios" : "android",
  // model: DeviceInfo.model,
  deviceType: '',
  productId: "6007",
  adPlatform: "weixin",

}

@ccclass
export default class ReportManager {
  static baseUrl = 'https://mini.quminglemei.com'
  // const baseUrl = 'http://119.23.179.197:8203'

  // banner_ad: "adunit-7c3c2a0a423cb111"
  // incentive_video_ad: "adunit-15c669955f88e175"
  // intersArr: ["adunit-4bce969ba8359203"]
  // native_ad: "adunit-54c4724d8ef2a5b7"
  // screen_ad: "adunit-4bce969ba8359203"

  static configObj = {
    banner_ad: "adunit-5fb8fba1f71d99aa",
    incentive_video_ad: "adunit-19007613c09ee9c7",
    intersArr: "adunit-6cba94f4bebc9cb8",
    native_ad: "adunit-8801d71617a2d5d2"
  };

  static inited = false;


  /**
   * 读取广告配置
   * @param data 
   * @returns 
   */
  static getAdConfig(data = {}) {
    if(!wx){
      return {};
    }
    const query = { ...wx.getLaunchOptionsSync().query };
    console.log('AesEncode1',query)
try {
      // 存储版本信息
const osVersion = wx.getAppBaseInfo().SDKVersion
const DeviceInfo = wx.getDeviceInfo()

reportParams.osVersion= osVersion;
reportParams.osType= DeviceInfo.system.indexOf('iOS') !== -1 ? "ios" : "android";
reportParams.model= DeviceInfo.model;
} catch (error) {
  console.log('eeeeeeee',error)
}
    globalQuery = query
    const ext = encodeURIComponent(AesEncode(JSON.stringify({
      ...query,
    })));
    console.log('AesEncode2',ext,ReportManager)
    //  const ext = encodeURIComponent(AesEncode('{"cid":"3","strategyId":"1","channel":"8_6007_6007001","subChannel":"dsp_1","brandD":"2","click_id":"__YOYO_REQ_ID__","imei":"__IMEI__","oaid":"__OAID__","JPLink":"/xz_bq/pages/function_list/index"}'))
  //  第一次请求时，上报-1
    ReportManager.reportAd({
      actionType:-1,
      pageName:"wx161df3134c5d362f",
    })
    let self = this;
    wx.getSystemInfo().then(res => {
      console.log('SystemInfoSystemInfoSystemInfo', res)
      systemInfo = {
        screenWidth: res.screenWidth,
        screenHeight: res.screenHeight,
        osVersion: res.system,

      }
    })

    return new Promise((resolve, reject) => {
      if (this.inited) {
        resolve(self.configObj);
        return;
      }
      this.inited = true;
      try {
        wx.request({
          url: this.baseUrl + "/ad/adConfig/getAdId",
          cachetime: "30",
          method: "POST",
          data: {
            productId: "6007",
            ext
          },
          success: function (e) {
            console.log('1233333333333333333', e);
            let res = e.data.data ?? {};

            if (res.spaceIds && Array.isArray(res.spaceIds) && res.spaceIds.length > 0) {
              let configObjMap = {
                'native_template': 'native_ad', // 原生
                'inters': 'screen_ad', //插屏
                'video': 'video_ad', // 视频广告
                'reward_video': 'incentive_video_ad', //激励视频
                'banner': 'banner_ad' //banner广告
              };

              res.spaceIds.forEach(el => {
                self.configObj[configObjMap[el.spaceType]] = el.spaceId;
              });

              resolve(self.configObj);
            } else {
              reject({});
            }
          },
          fail: function (e) {
            self.inited = false;
            reject({});
          },
        });
      } catch (error) {
        this.inited = false;
        reject({});
      }
    });
  }




  /**
   * 页面上报，调用 reportPage({ageName:"xz/bq/index/index",Event:'pageShow',actionType:'-3',actionName:''})
   * actyonType -3 进入 -4 离开
   * @param data 
   */
  static reportPage = (data = {}) => {
    let query = { ...globalQuery }

    if (data?.MSG) {
      query['getAdQuery'] = data.MSG ? data.MSG : ''
    }
    const ext = encodeURIComponent(AesEncode(JSON.stringify({
      ...reportParams,
      ...systemInfo,
      ...data,

      subChannel: query.subChannel ?? '',
      brandD: query.brandD ?? '',
      channel: query.channel ?? '',
      message: query ? JSON.stringify(query) : '',
      uuid: query.uuid ? query.uuid : reportParams.uuid,
      vvid: query.vvid ? query.vvid : reportParams.vvid,
      uuRequestId: Utils.createUURequrstId(),
      clickId: query['clickid'] ? query['clickid'] : query['click_id'] ? query['click_id'] : "",
      imei: query['imei'] ? query['imei'] : "",
      oaid: query['oaid'] ? query['oaid'] : "",
    })))

    wx.request({
      url: ReportManager.baseUrl + "/ad/report/adReport",
      cachetime: "30",
      method: "POST",
      data: {
        ext

      },
      success: function (e) { }
    })
  }


/**
 * 广告上报
 * reportAd({
            actionType: 2,
            pageName: pageName,
            adType: 'inters',
            spaceId: adUnitId,
            actionName: '加载插屏失败'+a.errMsg,
          })
 * @param data 
 */
  static reportAd = (data = {}) => {
    let query = { ...globalQuery }
    const ext = encodeURIComponent(AesEncode(JSON.stringify({
      ...reportParams,
      ...systemInfo,
      ...data,
      uuid: query.uuid ? query.uuid : reportParams.uuid,
      vvid: query.vvid ? query.vvid : reportParams.vvid,
      uuRequestId: Utils.createUURequrstId(),
      clickId: query['clickid'] ? query['clickid'] : query['click_id'] ? query['click_id'] : "",
      imei: query['imei'] ? query['imei'] : "",
      oaid: query['oaid'] ? query['oaid'] : "",
      subChannel: query.subChannel ?? '',
      brandD: query.brandD ?? '',
      channel: query.channel ?? '',
      appMode: 1,
      configMode: 1,
      message: query ? JSON.stringify(query) : '',
      spaceKey: "error_show_ad",
    })))
    wx.request({
      url: ReportManager.baseUrl + "/ad/report/adReport",
      cachetime: "30",
      method: "POST",
      data: {
        ext
      },
      success: function (e) { }
    })
  }


  static reportEvent = (data = {}) => {
    let query = { ...globalQuery }
    const ext = encodeURIComponent(AesEncode(JSON.stringify({
      ...reportParams,
      ...systemInfo,
      ...data,
      uuid: query.uuid ? query.uuid : reportParams.uuid,
      vvid: query.vvid ? query.vvid : reportParams.vvid,
      clickId: query['click_id'] ? query['click_id'] : "",
      imei: query['imei'] ? query['imei'] : "",
      oaid: query['oaid'] ? query['oaid'] : "",
    })))
    wx.request({
      url: ReportManager.baseUrl + "/ad/report/eventReport",
      cachetime: "30",
      method: "POST",
      data: {
        ext
      },
      success: function (e) { }
    })
  }

  // 
  // public adIndex = 0; // 初始索引为0
  // public screenIndex = 0; // 初始索引为0
  // public redomeAd(){
  //   const redemeAdFn = () => {
  //     try {
  //       if (global.adConfig[global.channel].intersArr) {
  //         const createArrayIterator = (arr) => {
  //           const result = arr[adIndex]; // 获取当前索引对应的数组项
  //           adIndex = (adIndex + 1) % arr.length; // 更新索引，取余确保循环返回
  //           return result;
  //         }
  //         let adid = createArrayIterator(global.adConfig[global.channel].intersArr)
  //         console.log('addddddd', adid, new Date().getTime())

  //         return adid
  //       }

  //       return global.adConfig[global.channel ?? 1].screen_ad
  //     } catch (error) {
  //       return ""
  //     }
  //   }
  //   if (global.query.strategyId && (global.query.strategyId == 4 || global.query.strategyId == 3)) {

  //     return ""
  //   }
  //   if (global.query.strategyId && global.query.strategyId == 2) {

  //     if (screenIndex % 2 !== 0) {

  //       screenIndex += 1
  //       return redemeAdFn()
  //       // 奇数
  //     } else {
  //       screenIndex += 1
  //       return ""
  //     }
  //   }
  //   return redemeAdFn()




  // }


  // public redomeAdVideo(){
  //   // callCount++;
  //   // if (callCount <= 3) {
  //   //   return 1;
  //   // } else {
  //   //   videoIndex = (videoIndex % 2) + 1;
  //   //   return videoIndex;
  //   // }
  //   // videoIndex = (videoIndex % 2) + 1;
  //   // return videoIndex;
  //   return 2
  // };

}
